import { useEffect, useState, useRef } from "react";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import { useLocation, history } from "umi";
import {
  orderDetail,
  fetchPackageInfo,
  fetchAddressList,
  updateAddress,
  deliverySubmitJdOrder,
  recoverySubmitJdOrder,
  withholdingDeposit,
  getPrintData,
} from "@/api/order";
import {
  Table,
  Typography,
  Descriptions,
  Collapse,
  message,
  Popconfirm,
  Image,
  Button,
  Modal,
} from "antd";
import {
  filterOrderPackageStatusOptions,
  filterSchoolbagStatusOptions,
} from "@/const";
import { LeftOutlined } from "@ant-design/icons";
import ProForm, {
  ModalForm,
  ProFormSelect,
  ProFormDigit,
  ProFormTextArea,
} from "@ant-design/pro-form";
import sendMsg2Print from "@/ws";
import { fetchInfo } from "@/api/companyAddress";
import UploadFile from "@/components/UploadFile";

const { Paragraph } = Typography;
export default () => {
  const location = useLocation();
  const { orderId } = location.query;
  const [info, setInfo] = useState({});
  const [addressInfo, setAddressInfo] = useState({});

  const getInfo = async () => {
    const res = await fetchPackageInfo({ orderId });
    if (res.data) {
      setInfo(res.data);
    }
  };

  const getAddressInfo = async () => {
    const res = await fetchInfo();
    if (res.data) {
      setAddressInfo(res.data);
    }
  };

  useEffect(() => {
    getInfo();
    getAddressInfo();
  }, []);

  const columns = [
    {
      title: "商品信息",
      dataIndex: "shop",
      search: false,
      render: (_, record) => {
        return (
          <>
            <div key={record.id} style={{ display: "flex", marginBottom: 10 }}>
              <Image width={80} height={80} src={record.picture} />
              <div style={{ marginLeft: 8 }}>
                <div>{record.title}</div>
              </div>
            </div>
          </>
        );
      },
    },
    {
      title: "单价",
      dataIndex: "unitPrice",
      render: (_, record) => {
        return `￥${record.unitPrice}`;
      },
    },
    {
      title: "数量",
      dataIndex: "quantity",
    },
    {
      title: "小计",
      dataIndex: "total",
      render: (_, record) => {
        return `￥${record.quantity * record.unitPrice}`;
      },
    },
  ];

  const renderEditModal = (record) => {
    return (
      <ModalForm
        title="编辑"
        trigger={
          <Button type="primary" style={{ marginRight: 10 }}>
            编辑
          </Button>
        }
        initialValues={{ ...record }}
        onFinish={async (values) => {
          const res = await updateAddress({ id: record.id, ...values });
          if (res.code == 200) {
            message.success("编辑成功");
            getInfo();
            return true;
          }
        }}
      >
        <ProFormSelect
          name="addressId"
          label="地址"
          allowClear
          request={async () => {
            const res = await fetchAddressList({
              createUser: info.createUser,
            });
            return res.data.map((item) => {
              return {
                value: item.id,
                label: `${item.province}${item.city}${item.area}${item.detail}`,
              };
            });
          }}
          rules={[{ required: true, message: "请选择地址" }]}
        />
      </ModalForm>
    );
  };

  // 联系物流回收书包
  const renderConcatModal = (record) => {
    return (
      <ModalForm
        title="联系物流回收书包"
        trigger={
          <Button type="primary" style={{ marginRight: 10 }}>
            联系物流回收书包
          </Button>
        }
        initialValues={{ ...record }}
        onFinish={async (values) => {
          const res = await recoverySubmitJdOrder({
            schoolbagOrderId: orderId,
            schoolbagReadRecordId: record.id,
          });
          if (res.data) {
            message.success("下单成功");
            getInfo();
            return true;
          }
        }}
        submitter={{
          // 配置按钮文本
          searchConfig: {
            submitText: "确定下单",
          },
          render: (props, dom) => dom[1],
        }}
      >
        <ProCard title="寄件人">
          <div>寄件人：{record.receiver}</div>
          <div>联系电话：{record.mobile}</div>
          <div>
            寄件地址： {record.province}
            {record.city}
            {record.area}
            {record.detail}
          </div>
        </ProCard>
        <ProCard title="收件人">
          <div>收件人：{addressInfo.name}</div>
          <div>联系电话：{addressInfo.mobile}</div>
          <div>收件地址：{addressInfo.address}</div>
        </ProCard>
      </ModalForm>
    );
  };

  // 押金扣除
  const renderDeductionMoney = (record) => {
    return (
      <ModalForm
        title="押金扣除"
        trigger={
          <Button type="primary" style={{ marginLeft: 10 }}>
            押金扣除
          </Button>
        }
        submitter={{
          // 配置按钮文本
          searchConfig: {
            submitText: "确定扣除",
          },
          render: (props, dom) => dom[1],
        }}
        initialValues={{ ...record }}
        onFinish={async (values) => {
          const res = await withholdingDeposit({ id: record.id, ...values });
          if (res.data) {
            message.success("扣除成功");
            getInfo();
            return true;
          }
        }}
      >
        <ProFormTextArea
          fieldProps={{
            rows: 5,
            maxLength: 2000,
            showCount: true,
          }}
          name="deductionReason"
          label="损坏说明"
          placeholder="请输入损坏说明"
          rules={[{ required: true, message: "请输入损坏说明" }]}
        />
        <ProForm.Item
          label="上传图片"
          name="deductionImg"
          rules={[{ required: true, message: "请上传图片" }]}
        >
          <UploadFile maxCount={1} />
        </ProForm.Item>

        <ProFormDigit
          label="押金扣除"
          name="deductionMoney"
          placeholder="请输入"
          addonAfter="元"
          fieldProps={{
            precision: 2,
          }}
          rules={[{ required: true, message: "请输入" }]}
        />
      </ModalForm>
    );
  };

  // 查看申诉
  const renderViewModal = (record) => {
    return (
      <ModalForm
        title="查看申诉"
        trigger={
          <Button type="primary" style={{ marginRight: 10 }}>
            查看用户申诉
          </Button>
        }
        initialValues={{ ...record }}
        onFinish={async (values) => {
          const res = await orderDetail({ orderId, ...values });
          if (res.code == 200) {
            message.success("下单成功");
            getInfo();
          }
        }}
        submitter={false}
      ></ModalForm>
    );
  };

  return (
    <PageContainer
      loading={!info?.schoolbag?.name}
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            书包详情
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProCard
        style={{ marginTop: 20 }}
        title={
          <h2>
            <span>{info?.schoolbag?.name}</span>
            <span style={{ marginLeft: 50 }}>￥{info.orderAmount}</span>
          </h2>
        }
        bordered
        extra={filterSchoolbagStatusOptions(info.schoolbagStatus)}
      >
        <Descriptions column={3}>
          <Descriptions.Item label="订单号">{info?.orderNo}</Descriptions.Item>
          <Descriptions.Item label="订单状态">
            {filterOrderPackageStatusOptions(info?.orderStatus)}
          </Descriptions.Item>

          <Descriptions.Item label="购买时间">
            {info?.createTime}
          </Descriptions.Item>
          <Descriptions.Item label="下单人(用户-手机号)">
            {info.createUserName}-{info.createUserPhone}
          </Descriptions.Item>
          <Descriptions.Item label="收货人(用户-手机号)">
            {info.receiver}-{info.mobile}
          </Descriptions.Item>
          <Descriptions.Item label="期数">
            {`${info.schoolbagCurrentNum || "-"} / ${
              info.schoolbag?.cycle || 12
            }
            `}
          </Descriptions.Item>
          <Descriptions.Item label="组号">
            {info?.schoolbagGroupCode}
          </Descriptions.Item>
        </Descriptions>
      </ProCard>
      {info.readRecordVOList?.map((item, index) => {
        return (
          <ProCard
            style={{ marginTop: 20 }}
            title={`第${index + 1}期`}
            actions={[
              // 服务状态 0待发货(商家) 1已发货(商家) 2已收货 (用户) 3已发货(用户)  4已收货(商家)
              // 订单状态 1待支付 2已支付 3已退款 4退款中 5已取消 6售后中 7售后退款中 8售后驳回 9售后已退款

              <div style={{ display: "flex", justifyContent: "flex-end" }}>
                {/* 订单状态为已支付 并且 待发货(商家) 才能发货和编辑 */}
                {info.orderStatus == 2 && item.serviceStatus == 0 && (
                  <>
                    {renderEditModal(item)}
                    <Popconfirm
                      title="确定发货?"
                      onConfirm={async () => {
                        const res = await deliverySubmitJdOrder({
                          schoolbagOrderId: orderId,
                          schoolbagReadRecordId: item.id,
                        });
                        if (res.data) {
                          getInfo();
                        }
                      }}
                    >
                      <Button type="primary" style={{ marginRight: 10 }}>
                        发货
                      </Button>
                    </Popconfirm>
                  </>
                )}

                {/* 订单状态为已支付 并且 已发货(商家) 才能打印运单 */}
                {info.orderStatus == 2 && item.serviceStatus == 1 && (
                  <Popconfirm
                    key="print"
                    title="确定打印运单?"
                    onConfirm={async () => {
                      const res = await getPrintData({
                        schoolbagOrderId: orderId,
                        schoolbagReadRecordId: item.id,
                      });
                      if (res.data) {
                        // webSocket 调起打印
                        sendMsg2Print(res.data);
                        message.success("打印成功");
                        getInfo();
                      }
                    }}
                  >
                    <Button type="primary" style={{ marginRight: 10 }}>
                      打印运单
                    </Button>
                  </Popconfirm>
                )}

                {/* 管理端下物流单-用户端不需要手动点击 */}
                {[2, 6, 7, 8, 9].includes(info.orderStatus) &&
                  item.serviceStatus == 2 &&
                  renderConcatModal(item)}
              </div>,
            ]}
            extra={filterSchoolbagStatusOptions(item.serviceStatus)}
          >
            <Descriptions column={3}>
              <Descriptions.Item label="书包号">
                {item.schoolbagGroupBagCode}
              </Descriptions.Item>
              <Descriptions.Item label="书本数量">
                {item.schoolbagBookNum}本
              </Descriptions.Item>
              <Descriptions.Item label="发货日期">
                {item.expressDeliveryTime}
              </Descriptions.Item>
              <Descriptions.Item label="收货姓名电话">
                {item.receiver}-{item.mobile}
              </Descriptions.Item>
              <Descriptions.Item label="收货地址">
                {item.province}
                {item.city}
                {item.area}
                {item.detail}
              </Descriptions.Item>

              <Descriptions.Item label="用户提交归还日期">
                {item.actualReturnTime}
              </Descriptions.Item>
              {item.expressDeliveryWaybillCode && (
                <Descriptions.Item label="发货物流单号">
                  <Paragraph copyable>
                    {item.expressDeliveryWaybillCode}
                  </Paragraph>
                </Descriptions.Item>
              )}
              {item.userConfirmTime && (
                <Descriptions.Item label="用户收货日期">
                  {item.userConfirmTime}
                </Descriptions.Item>
              )}
              {item.expressReturnWaybillCode && (
                <Descriptions.Item label="收货物流单号">
                  <Paragraph copyable>
                    {item.expressReturnWaybillCode}
                  </Paragraph>
                </Descriptions.Item>
              )}
              {item.companyConfirmTime && (
                <Descriptions.Item label="确认收货日期">
                  {item.companyConfirmTime}
                </Descriptions.Item>
              )}
              {item.deductionMoney && (
                <Descriptions.Item label="押金扣除">
                  <span style={{ color: "red" }}>￥{item.deductionMoney}</span>
                  {item.isDeductionDeposit ? "" : renderDeductionMoney(item)}
                </Descriptions.Item>
              )}
            </Descriptions>

            <Descriptions column={1} title="本期书本">
              <Descriptions.Item>
                <Collapse defaultActiveKey={["1"]}>
                  <Collapse.Panel header="" key="1">
                    {item.bookList?.map((sub) => {
                      return (
                        <span style={{ marginRight: 10 }}>
                          <Image width={80} height={80} src={sub.picture} />
                        </span>
                      );
                    })}
                  </Collapse.Panel>
                </Collapse>
              </Descriptions.Item>
            </Descriptions>
            {item.appealDesc ? (
              <Descriptions column={1} title="用户申述">
                <Descriptions.Item label="申述说明">
                  {item.appealDesc}
                </Descriptions.Item>
                <Descriptions.Item label="申述图片">
                  <Image width={80} height={80} src={item.appealPicture} />
                </Descriptions.Item>
                {/* <Descriptions.Item>{renderViewModal(item)}</Descriptions.Item> */}
              </Descriptions>
            ) : (
              ""
            )}
          </ProCard>
        );
      })}
    </PageContainer>
  );
};
